package com.yunduo.world.worker;

import com.google.protobuf.ByteString;
import com.yunduo.world.entity.EntityInfo;
import com.yunduo.world.entity.NetRoom;
import com.yunduo.world.constant.NetWorkRoomConstant;
import com.yunduo.world.utils.YStringUtils;
import com.yunduo.world.constant.NetWorkConstant;
import com.yunduo.world.factory.ChannelWorker;
import com.yunduo.world.utils.ClientUtils;
import com.yunduo.world.utils.EntityBuild;
import com.yunduo.world.utils.NetRoomUtils;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理其他信息
 */
@Slf4j
public class RoomWorker extends ChannelWorker {
    // 匹配器
    @Override
    public void execute() {
        EntityInfo.Message msg = getMsg().getMsg();
        String context = msg.getContext();
        // 匹配是否有人游玩
        if (NetWorkRoomConstant.IS_HAVE_USER_PLAYING.equals(context)) {
            have_user_playing();
        }
        // 创建房间
        if (NetWorkRoomConstant.CREATE_ROOM.equals(context)) {
            create_room();
        }
        // 加入房间
        if (NetWorkRoomConstant.JOIN_ROOM.equals(context)){
            join_room();
        }
        // 是否接受加入房间
        if (NetWorkRoomConstant.IS_ACCEPT_JOIN.equals(context)){
            is_accept_join();
        }
        // 房主处理加入房间信息
        if (NetWorkRoomConstant.MASTER_ROOM_RESULT.equals(context)) {
            master_room_result();
        }
        // 拉取当前房间玩家列表
        if (NetWorkRoomConstant.ROOM_PLAYERS_INFO.equals(context)) {
            room_players_info();
        }
    }

    // 房间其他玩家信息
    private void room_players_info() {
        EntityInfo.Message msg = getMsg().getMsg();
        String currentRoomId = msg.getData().toString(CharsetUtil.UTF_8);
        NetRoom netRoom = NetRoomUtils.get(currentRoomId);
        StringBuffer userList= new StringBuffer();
        if (netRoom != null){
            userList.append(netRoom.getRoomMaster()+NetWorkConstant.split_level_two+netRoom.getRoomMaster());
            userList.append(NetWorkConstant.split);
            netRoom.getRoomVisitor().forEach(item->{
                userList.append(item+NetWorkConstant.split_level_two+item+NetWorkConstant.split);
            });
        }
        byte[] bytes = YStringUtils.UTF8String(userList.toString());
        EntityInfo.Entity entity = buildMessage(NetWorkRoomConstant.ROOM_PLAYERS_INFO, NetWorkConstant.OK, ByteString.copyFrom(bytes));
        getCtx().writeAndFlush(entity);
    }

    // 房主 同意/拒绝 加入房间信息
    private void master_room_result() {
        EntityInfo.Message msg = getMsg().getMsg();
        // 获取用户id
        String uId = msg.getData().toString(CharsetUtil.UTF_8);
        // 用户连接
        Channel channel = ClientUtils.get(uId);
        if (msg.getStatus()) {
            // 添加到房主房间
            String id = ClientUtils.get(getCtx().channel());
            NetRoom netRoom = NetRoomUtils.get(id);
            List<String> roomVisitor = netRoom.getRoomVisitor();
            roomVisitor.add(uId);
            getCtx().writeAndFlush(buildMessage(NetWorkRoomConstant.MASTER_ROOM_RESULT,NetWorkConstant.OK));
            channel.writeAndFlush(buildMessage(NetWorkRoomConstant.IS_ACCEPT_JOIN,NetWorkConstant.OK));
        } else {
            channel.writeAndFlush(buildMessage(NetWorkRoomConstant.IS_ACCEPT_JOIN,NetWorkConstant.NOT_OK));
        }

    }

    // 创建房间
    private void create_room() {
        EntityInfo.Message msg = getMsg().getMsg();
        ByteString data = msg.getData();
        String id = ClientUtils.get(getCtx().channel());
        NetRoom netRoom = NetRoomUtils.get(id);
        if (netRoom != null){
            netRoom.setRoomData(data);
        } else {
            NetRoom room = new NetRoom();
            room.setRoomMaster(id);
            room.setRoomData(data);
            room.setRoomVisitor(new ArrayList<>());
            NetRoomUtils.add(room);
        }
        EntityInfo.Entity message = buildMessage(msg.getContext(), NetWorkConstant.OK);
        getCtx().writeAndFlush(message);
    }

    // 是否有人游玩 响应用户id和在线人数
    public void have_user_playing(){
        List<NetRoom> all = NetRoomUtils.getAll();
        EntityInfo.Entity entity;
        if (all.size() != 0) {
            // 响应所有用户房间数据
            StringBuffer buffer = new StringBuffer();
            all.forEach(item-> {
                buffer.append(item.getRoomMaster()
                        +NetWorkConstant.split_level_two
                        +(item.getRoomVisitor().size()+1)
                        +NetWorkConstant.split);
            });
            byte[] bytes = YStringUtils.UTF8String(buffer.toString());
            entity = buildMessage(NetWorkRoomConstant.IS_HAVE_USER_PLAYING, NetWorkConstant.OK,ByteString.copyFrom(bytes));
        } else {
            // 没有房间
            entity = buildMessage(NetWorkRoomConstant.IS_HAVE_USER_PLAYING, NetWorkConstant.NOT_OK);
        }
        getCtx().writeAndFlush(entity);
    }

    // 加入房间 获取地图数据
    public void join_room(){
        ByteString data = getMsg().getMsg().getData();
        String id = new String(data.toByteArray(), CharsetUtil.UTF_8);
        NetRoom netRoom = NetRoomUtils.get(id);
        EntityInfo.Entity entity;
        EntityInfo.Entity rootEntity;
        if (NetRoomUtils.roomIsNotEmpty(netRoom)){
             entity = buildMessage(NetWorkRoomConstant.JOIN_ROOM, NetWorkConstant.OK,netRoom.getRoomData());
             // id + 名称
             String userInfo = ClientUtils.get(getCtx().channel())+NetWorkConstant.split_level_two+ClientUtils.get(getCtx().channel());
             rootEntity = buildMessage(NetWorkRoomConstant.JOIN_ROOM, NetWorkConstant.OK, ByteString.copyFrom(userInfo.getBytes(CharsetUtil.UTF_8)));
        } else {
            entity = buildMessage(NetWorkRoomConstant.JOIN_ROOM,NetWorkConstant.NOT_OK);
            rootEntity = entity;
        }
        getCtx().writeAndFlush(entity);
        // 通知房主用户已加入
        Channel roomMaster = ClientUtils.get(id);
        roomMaster.writeAndFlush(rootEntity);
    }

    //是否同意加入房间
    public void is_accept_join(){
        // 房主信息
        byte[] byteArray = getMsg().getMsg().getData().toByteArray();
        String masterId = new String(byteArray, CharsetUtil.UTF_8);
        Channel masterChannel = ClientUtils.get(masterId);
        // 玩家信息
        String id = ClientUtils.get(getCtx().channel());
        // 组装id+名称 转换字节数据
        byte[] currentUserData = (id+NetWorkConstant.split_level_two+id).getBytes(CharsetUtil.UTF_8);
        EntityInfo.Entity masterEntity = buildMessage(NetWorkRoomConstant.IS_ACCEPT_JOIN,NetWorkConstant.OK,ByteString.copyFrom(currentUserData));
        // 响应房主,请求玩家信息。
        masterChannel.writeAndFlush(masterEntity);
    }

    /**
     * 数据构建
     * @param context
     * @param status
     * @return
     */
    public EntityInfo.Entity buildMessage(String context,boolean status){
        return EntityBuild.buildMessage(NetWorkRoomConstant.ROOM,context,status);
    }

    public EntityInfo.Entity buildMessage(String context,boolean status,ByteString bytes){
        return EntityBuild.buildMessage(NetWorkRoomConstant.ROOM,context,status,bytes);
    }
}
